//
//  KeHuXiangQingViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/17.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "KeHuXiangQingViewController.h"
#import "KeHuXiangQingGenJinJiLuViewController.h"
#import "KeHuXiangXinXiViewController.h"
#import "KeHuXiangQingDingBuView.h"
#import "KeHuXiangQingBottomView.h"
#import "KeHuXiangQingCaoZuoRiZhiViewController.h"
#import "JMPopupMenuView.h"

#import "GenJinJiLuViewController.h"
#import "AlertRemindView.h"
#import "GongHaiFenPeiViewController.h"
#import "XinJianKeHuViewController.h"

#import "ZhuiJiaKuanXiangViewController.h"

#import "KeHuChengJiaoZhuangTaiViewController.h"
#import "ChengJiaoZhungTaiHuiTuiViewController.h"
@interface KeHuXiangQingViewController (){
    NSMutableArray *quanXianArray;
}

@property (nonatomic,strong) NSDictionary *dataDictionary;


//存放排序方式数组
@property (nonatomic, strong) NSMutableArray *dataArr;
@end

@implementation KeHuXiangQingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupNavBar];


    // 设置自定义导航栏背景图片
    self.customNavBar.barBackgroundImage = [UIImage imageNamed:@"导航栏"];
    
    
    
    [self.customNavBar setOnClickRightButton:^{
        
        NSString *url = [NSString stringWithFormat:@"/crmCustomer/star/%@",_customerId];
        [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
            if(!error){
                if([GetHandleString(_dataDictionary, @"star") integerValue] == 1){
                    [ZZPUtils showWarning:@"已取消关注"];
                    [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情关注")];
                }else{
                    [ZZPUtils showWarning:@"已添加关注"];
                    [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情已关注")];
                }
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"star") boolValue]] forKey:@"star"];
                _dataDictionary = dataDic;
            }
        }];
    }];
    
    

//    [self zaiRuView];
    [self getCoustomerInfoByCoustomerId];
    
    
    KeHuXiangQingBottomView *view = [KeHuXiangQingBottomView view];
    [self.view addSubview:view];
    view.sd_layout
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view)
    .heightIs(97);
    
    view.manageClickBlock = ^(NSInteger index) {
        if(index == 100){
            //            写记录
            GenJinJiLuViewController *xieJiLu = [[GenJinJiLuViewController alloc] init];
            xieJiLu.activityTypeId = _customerId;
            xieJiLu.addSuccessClickBlock = ^{
                [self zaiRuView];
            };
            [self.navigationController pushViewController:xieJiLu animated:YES];
        }else if(index == 101){
            //            编辑
            XinJianKeHuViewController *gongHai = [[XinJianKeHuViewController alloc] init];
            gongHai.shiBuShiZongLanKeHu = _shiBuShiZongLanKeHu;
            gongHai.customerId = GetHandleString(_dataDictionary, @"customerId");
            gongHai.manageClick = ^(NSInteger index) {
                [self getCoustomerInfoByCoustomerId];
            };
            [self.navigationController pushViewController:gongHai animated:YES];
        }else if(index == 102){
            //            电话
            if([GetHandleString(_dataDictionary, @"mobile") length] > 0){
                [ZZPUtils telephoneForAppWithNum:GetHandleString(_dataDictionary, @"mobile")];
            }else{
                [ZZPUtils showWarning:@"暂无联系方式"];
            }
        }else if(index == 103){
            //            更多
            self.dataArr = [NSMutableArray array];
            
            NSString *dealStatus = @"取消成交";
            if([GetHandleString(_dataDictionary, @"dealStatus") integerValue] == 0){
                dealStatus = @"去成交";
            }
            
            JMPopupMenuView *menuView = [JMPopupMenuView new];
            menuView.targetView = view.moreButtton;
    
            menuView.shouldShowSeparator = NO;
            menuView.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
            
            NSMutableArray *itemsArray = [NSMutableArray array];
            for (NSString *name in quanXianArray) {
                NSString *result = name;
                if([name isEqualToString:@"成交"]){
                    result = dealStatus;
                }
                
                JMMenuItem *item =  [JMMenuItem itemWithImage:nil title:result handler:^(JMMenuItem * _Nonnull item) {
                    NSLog(@"%@",item.title);
                    if([name isEqualToString:@"转移"]){
                        GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
                        gongHai.currentType = 3;
                        gongHai.customerId = _customerId;
                        [self.navigationController pushViewController:gongHai animated:YES];
                    }else if([name isEqualToString:@"删除"]){
                        [self performAfter:0.3 block:^{
                            AlertRemindView *view = [AlertRemindView view];
                            [ZZPUtils showAlertViewWithView:view andController:self];
                      
                            view.contentLabel.text = @"您确定要删除该客户吗？";
                       
                            view.manageClickBlock = ^(NSInteger index) {
                                [self dismissViewControllerAnimated:YES completion:nil];
                                if(index == 102){
                                    [self shanChuYongHu];
                                }
                            };
                        }];
                    }else  if([name isEqualToString:@"共享"]){
                        GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
                        gongHai.currentType = 2;
                        gongHai.customerId = _customerId;
                        [self.navigationController pushViewController:gongHai animated:YES];
                    }else  if([name isEqualToString:@"成交"]){
//                        [self performAfter:0.3 block:^{
//                            AlertRemindView *view = [AlertRemindView view];
//                            [ZZPUtils showAlertViewWithView:view andController:self];
//                            if([dealStatus isEqualToString:@"已成交"]){
//                                view.contentLabel.text = @"您确定要将客户更改为已成交吗？";
//                            }else{
//                                view.contentLabel.text = @"您确定要将客户更改为未成交吗？";
//                            }
//                            
//                            
//                            view.manageClickBlock = ^(NSInteger index) {
//                                [self dismissViewControllerAnimated:YES completion:nil];
//                                
//                                if(index == 102){
//    //                                成交
//                                    [self chengJiaoKeHu];
//                                }
//                                
//                            };
//                        }];
                        if([dealStatus isEqualToString:@"去成交"]){
                            KeHuChengJiaoZhuangTaiViewController *chengJiao = [[KeHuChengJiaoZhuangTaiViewController alloc] init];
                            chengJiao.ids = GetHandleString(_dataDictionary, @"customerId");
                            chengJiao.manageClickBlock = ^(NSInteger index) {
                                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
                                _dataDictionary = dataDic;
                                [self getCoustomerInfoByCoustomerId];
                            };
                            [self.navigationController pushViewController:chengJiao animated:YES];
                        }else{
                            ChengJiaoZhungTaiHuiTuiViewController *chengJiao = [[ChengJiaoZhungTaiHuiTuiViewController alloc] init];
                            chengJiao.ids = GetHandleString(_dataDictionary, @"customerId");
                            chengJiao.manageClickBlock = ^(NSInteger index) {
                                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
                                _dataDictionary = dataDic;
                                [self getCoustomerInfoByCoustomerId];
                            };
                            [self.navigationController pushViewController:chengJiao animated:YES];
                        }
                    }else  if([name isEqualToString:@"放入公海"]){
                        GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
                        gongHai.currentType = 1;
                        gongHai.customerId = GetHandleString(_dataDictionary, @"customerId");
                        [self.navigationController pushViewController:gongHai animated:YES];
                    }else  if([name isEqualToString:@"追加款项"]){
                        ZhuiJiaKuanXiangViewController *zhuiJia = [[ZhuiJiaKuanXiangViewController alloc] init];
                        zhuiJia.keHuDataDictionary = _dataDictionary;
                        zhuiJia.manageClickBlock = ^(NSInteger index) {
                            [self getCoustomerInfoByCoustomerId];
                        };
                        [self.navigationController pushViewController:zhuiJia animated:YES];
                    }else  if([name isEqualToString:@"标记无效"]){
                        GongHaiFenPeiViewController *gongHai = [[GongHaiFenPeiViewController alloc] init];
                        gongHai.currentType = 4;
                        gongHai.customerId = GetHandleString(_dataDictionary, @"customerId");
                        gongHai.manageResultBlock = ^(NSString * _Nonnull result, NSString * _Nonnull value) {
                            [self.navigationController popViewControllerAnimated:YES];
                            if (_manageClickResultBlock) {
                                _manageClickResultBlock(0);
                            }
                        };
                        [self.navigationController pushViewController:gongHai animated:YES];
                    }else  if([name isEqualToString:@"标记有效"]){
                        [self performAfter:0.3 block:^{
                            AlertRemindView *view = [AlertRemindView view];
                            [ZZPUtils showAlertViewWithView:view andController:self];
                            
                            view.contentLabel.text = @"确定要标记有效该客户吗？";
                            view.manageClickBlock = ^(NSInteger index) {
                                [self dismissViewControllerAnimated:YES completion:nil];
                                if(index == 102){
                                    [self biaoJiKeHuYouXiao];
                                }
                            };
                        }];
                    }
                }];
                [itemsArray addObject:item];
            }
            menuView.items = itemsArray;
        
        [menuView showWithAnimated:YES];
            
        }
    };
    
    view.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1600].CGColor;
    view.layer.shadowOffset = CGSizeMake(2,0);
    view.layer.shadowOpacity = 1;
    view.layer.shadowRadius = 10;
    
    CGFloat radius = 10; // 圆角值大小
    if (@available(iOS 11.0, *)){
        // 设置 左上 右上 圆角
        view.layer.cornerRadius = radius;
        view.layer.maskedCorners = kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner;
    }else {
        // 设置 左上 右上 圆角
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0,0,ScreenWidth,97) byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
        CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
        maskLayer.frame = CGRectMake(0,0,ScreenWidth,97);
        maskLayer.path = path.CGPath;
        view.layer.mask = maskLayer;
    }
    
    
    
}

//标记客户有效
- (void)biaoJiKeHuYouXiao{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@[_customerId] forKey:@"ids"];
    [paraDic setValue:@"0" forKey:@"isEffective"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/updateEffectiveById" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            [ZZPUtils showWarning:@"标记成功"];
            [self getCoustomerInfoByCoustomerId];
        }
    }];
}



//根据用户ID获取用户信息
- (void)getCoustomerInfoByCoustomerId{
    NSString *url = [NSString stringWithFormat:@"/crmCustomer/queryById/%@",_customerId];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:url andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            _dataDictionary = [info objectForKey:@"data"];
        
            if([GetHandleString(_dataDictionary, @"star") integerValue] == 0){
                [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情关注")];
            }else{
                [self.customNavBar wr_setRightButtonWithImage:LocalImagePath(@"客户详情已关注")];
            }
            
            [self zaiRuView];
            
            [self huoQuGeRenYongHuQuanXian];
        }
    }];
}

//获取个人权限
- (void)huoQuGeRenYongHuQuanXian{
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/adminRole/auth" andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSDictionary *data = [info objectForKey:@"data"];
            NSDictionary *crm = [data objectForKey:@"crm"];
            NSDictionary *customer = [crm objectForKey:@"customer"];
            quanXianArray = [NSMutableArray array];
            if([GetHandleString(customer, @"transfer") integerValue] == 1){
                [quanXianArray addObject:@"转移"];
            }
            
            if([GetHandleString(customer, @"delete") integerValue] == 1){
                [quanXianArray addObject:@"删除"];
            }
            
            [quanXianArray addObject:@"共享"];
            
            if([GetHandleString(customer, @"dealStatus") integerValue] == 1){
//                NSString *dealStatus = @"未成交";
//                if([GetHandleString(_dataDictionary, @"dealStatus") integerValue] == 0){
//                    dealStatus = @"已成交";
//                }
//                [quanXianArray addObject:dealStatus];
                
                [quanXianArray addObject:@"成交"];
            }
            
            if([GetHandleString(customer, @"putinpool") integerValue] == 1){
                [quanXianArray addObject:@"放入公海"];
            }
            if ([GetHandleString(customer, @"addamount") integerValue] == 1) {
                if([GetHandleString(_dataDictionary, @"dealStatus") integerValue] == 1 && [GetHandleString(_dataDictionary, @"dealAmount") floatValue] != [GetHandleString(_dataDictionary, @"paidAmount") floatValue]){
                    [quanXianArray addObject:@"追加款项"];
                }
            }
            if([GetHandleString(_dataDictionary, @"level") containsString:@"全域"]){
                if ([GetHandleString(customer, @"markvoid") integerValue] == 1) {
                    if([GetHandleString(_dataDictionary, @"isEffective") integerValue] == 0){
                        [quanXianArray addObject:@"标记无效"];
                    }else{
                        [quanXianArray addObject:@"标记有效"];
                    }
                }
            }
        }
    }];
}


//成交客户
- (void)chengJiaoKeHu{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
    [paraDic setValue:GetHandleString(_dataDictionary, @"customerId") forKey:@"ids"];
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/setDealStatus" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            [self performAfter:0.5 block:^{
                if(![GetHandleString(_dataDictionary, @"dealStatus") boolValue]){
                    [ZZPUtils showWarning:@"已成交"];
                }else{
                    [ZZPUtils showWarning:@"已取消成交"];
                }
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:_dataDictionary];
                [dataDic setValue:[NSString stringWithFormat:@"%d",![GetHandleString(_dataDictionary, @"dealStatus") boolValue]] forKey:@"dealStatus"];
                _dataDictionary = dataDic;
                
            }];
        }
    }];
    
}

//删除客户
- (void)shanChuYongHu{
    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/deleteByIds" andParas:@[GetHandleString(_dataDictionary, @"customerId")] andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            [self performAfter:0.5 block:^{
                [ZZPUtils showWarning:@"删除成功"];
            }];
            
            if(_manageClickResultBlock){
                _manageClickResultBlock(0);
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}





//是否领取成功
- (void)shiFouLingQuChengGong:(BOOL)isSuccess{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    if(isSuccess){
        view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
        view.titleLabel.text = @"领取成功";
        view.contentLabel.text = @"恭喜领取成功！";
    }else{
        view.topImage.image = LocalImagePath(@"公海领取弹窗失败");
        view.titleLabel.text = @"领取失败";
        view.contentLabel.text = @"超过库容，领取失败";
    }
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}

- (void)zaiRuView{
    //标题数组
    NSArray *data = @[@"跟进记录",@"详细信息",@"操作日志"];
    WMZPageParam *param = PageParam()
    .wTitleArrSet(data)
    .wMenuBgColorSet([UIColor whiteColor])
    .wMenuTitleColorSet(rgba(90, 98, 112, 1))
    .wMenuTitleSelectColorSet(rgba(24, 27, 37, 1))
    .wMenuAnimalTitleGradientSet(YES)
    .wMenuTitleWidthSet((ScreenWidth-0)/3)
    .wMenuHeightSet(64)
    .wMenuIndicatorColorSet(rgba(40, 120, 255, 1))
    .wMenuIndicatorWidthSet(48)
    .wMenuIndicatorHeightSet(3)
    .wMenuIndicatorRadioSet(1.5)
    .wMenuPositionSet(PageMenuPositionCenter)
    .wMenuTitleUIFontSet([UIFont systemFontOfSize:16])
    .wMenuTitleSelectUIFontSet([UIFont systemFontOfSize:16 weight:UIFontWeightMedium])
    //控制器数组
    .wViewControllerSet(^UIViewController *(NSInteger index) {
       
        if(index == 0){
            KeHuXiangQingGenJinJiLuViewController*vc = KeHuXiangQingGenJinJiLuViewController.new;
            vc.customerId = GetHandleString(_dataDictionary, @"customerId");
            return vc;
        }
        if(index == 2){
            KeHuXiangQingCaoZuoRiZhiViewController*vc = KeHuXiangQingCaoZuoRiZhiViewController.new;
            vc.customerId = GetHandleString(_dataDictionary, @"customerId");
            return vc;
        }
        KeHuXiangXinXiViewController*vc = KeHuXiangXinXiViewController.new;
        vc.customerId = GetHandleString(_dataDictionary, @"customerId");
        return vc;
    })
    .wCustomTabbarYSet(^CGFloat(CGFloat nowY) {
        return nowY;
    })
    .wBouncesSet(YES)
    //控制器结束切换
    .wEventEndTransferControllerSet(^(UIViewController *oldVC, UIViewController *newVC, NSInteger oldIndex, NSInteger newIndex) {
       NSLog(@"结束切换 %ld %ld",oldIndex,newIndex);
        _currentIndex = newIndex;
     })
    //悬浮开启
    .wTopSuspensionSet(NO)
    //顶部可下拉
    .wBouncesSet(NO)
    //头视图y坐标从导航栏开始
    .wFromNaviSet(NO)
    //导航栏透明度变化
    .wNaviAlphaSet(YES)
    .wMenuAnimalSet(PageTitleMenuAiQY)
    .wMenuDefaultIndexSet(_currentIndex)
    .wMenuHeadViewSet(^UIView *{
        KeHuXiangQingDingBuView *topView = [KeHuXiangQingDingBuView view];
        if(_juLiGongHaiNum.length > 0){
            topView.frame = CGRectMake(0, 0, ScreenWidth, NavaBarHeight+217);
            topView.gongHaiView.hidden = NO;
            topView.gongHaiViewHeight.constant = 38;
        }else{
            topView.frame = CGRectMake(0, 0, ScreenWidth, NavaBarHeight+217-38);
            topView.gongHaiView.hidden = YES;
            topView.gongHaiViewHeight.constant = 0;
        }
        
        topView.nameLabel.text = GetHandleString(_dataDictionary, @"customerName");
        topView.phoneLabel.text = GetHandleString(_dataDictionary, @"mobile");
        topView.fuZeRenLabel.text = GetHandleString(_dataDictionary, @"ownerUserName");
        topView.genJinShiJianLabel.text = GetHandleString(_dataDictionary, @"lastTime");
        topView.juLiGongHaiLabel.text = [NSString stringWithFormat:@"%ld天",[_juLiGongHaiNum integerValue]];
        topView.zhuangTaiLabel.text = GetHandleString(_dataDictionary, @"level");
        
        return topView;
    });
    //头部
    param.wCustomDataViewHeight = ^CGFloat(CGFloat nowY) {
        /// 再减掉父类的菜单高度
        if(_juLiGongHaiNum.length > 0){
            return nowY-NavaBarHeight-217-97;
        }
        return nowY-NavaBarHeight-217-97+38;
    };

    self.param = param;
}




- (void)setupNavBar{
    
    [self.view addSubview:self.customNavBar];
    [self.customNavBar wr_setBottomLineHidden:YES];
    if (self.navigationController.childViewControllers.count != 1) {
        [self.customNavBar wr_setLeftButtonWithImage:[UIImage imageNamed:@"返回"]];
    }
}



- (WRCustomNavigationBar *)customNavBar{
    if (_customNavBar == nil) {
        _customNavBar = [WRCustomNavigationBar CustomNavigationBar];
        _customNavBar.tintColor = [UIColor whiteColor];
        _customNavBar.titleLabelColor = rgba(24, 27, 37, 1);
        _customNavBar.barBackgroundImage = LocalImagePath(@"导航栏");
        _customNavBar.titleLabelFont = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
        _customNavBar.title = @"客户详情";
    }
    return _customNavBar;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



